Solve "Cross-Origin Request Blocked" in React frontend to an Express.js API?
Solve "Cross-Origin Request Blocked" in React frontend to an Express.js API?
509
03-Aug-2023
Updated on 04-Aug-2023
Aryan Kumar
04-Aug-2023There are a few ways to solve the cross origin request blocked error in React frontend to an Express.js API.
One way is to use the
Access-Control-Allow-Originheader in the Express.js API. This header tells the browser that the API is allowed to be accessed from any origin. To do this, you need to add the following header to the response:The
*wildcard allows requests from any origin. You can also specify a specific origin if you want to restrict access to only that origin.Another way to solve the cross origin request blocked error is to use the
CORSmiddleware in Express.js. The CORS middleware automatically adds theAccess-Control-Allow-Originheader to the response, as well as other headers that are required for cross origin requests. To use the CORS middleware, you need to install thecorspackage and then add the following code to your Express.js app:Finally, you can also solve the cross origin request blocked error by using the
proxyproperty in the package.json file of your React app. Theproxyproperty tells the React app to use a proxy server to make requests to the API. This can be helpful if you are developing your React app locally and the API is running on a different server. To use theproxyproperty, you need to add the following line to your package.json file:This line tells the React app to use the proxy server at
http://localhost:3000to make requests to the API. The proxy server will automatically add theAccess-Control-Allow-Originheader to the response, so you don't need to worry about adding it yourself.